const _FireManInfoModel = $.parseJSON( localStorage.getItem('msg') );
const _UserRoleRelationModel=$.parseJSON( localStorage.getItem('item') );
new Vue({
	el: '#ele',
	data: {
		form:[],
		time:'',
		map:'',
		marker1:'',
		marker2:'',
		Pointlng :"",
		PointLat :"",
		isShowRange:false,
		intRange:200000,
		arrRange:[500,1000,1500,2000], //检索范围
		arrStation:[],//微站
		arrAreaInfo:[],//火灾范围内的辖区信息
		arrStationCoordinate: [],// 存储坐标
		arrStationCheckIndex:[],//存储选中的下标
		multipleSelection:[],
		marker2s:[],
		loading:'',
        address:''
	},
	mounted() {
        var Vue = this
        setInterval(function(){
            var time = new Date();
            var y = time.getFullYear();
            var m = time.getMonth()+1;
            var d = time.getDate();
            var h = time.getHours();
            var mm = time.getMinutes();
            var s = time.getSeconds();
            Vue.time = y+'年'+Vue.add0(m)+'月'+Vue.add0(d)+'日  '+Vue.add0(h)+':'+Vue.add0(mm)+':'+Vue.add0(s);
        },1000)


        this.map = new AMap.Map('gd-map', {
            resizeEnable: true, //是否监控地图容器尺寸变化
            zoom: 11, //初始化地图层级
            center: [118.301306,35.190822] //初始化地图中心点
        });
        this.map.on('click', this.showInfoClick);


        $('body').on('click','.fire-set-adm-add',function(e){
            console.log(1)
            e.stopPropagation();
            $('.fire-set-adm-add').data('active',false);
            $(this).data('active',true)
            var left = $(this).offset().left+ $(this).outerWidth()+12
            var top = $(this).offset().top-$('.dialog-selec').outerHeight()/2+$(this).outerHeight()/2
            $('.dialog-selec').css({
                'top':top+'px',
                'left':left+'px'
            }).show()
        })
        $('body').on('click',function(e){
            e.stopPropagation();
            $('.dialog-selec').hide()
            $('.fire-set-adm-name').removeClass('border')
        })
        $('body').on('click','.fire-set-adm-name',function(e){
            e.stopPropagation();
            $('.fire-set-adm-name').removeClass('border')
            $(this).addClass('border')
        })
        $('body').on('click','.fire-set-adm-name .close',function(e){
            e.stopPropagation();
            $(this).parent('.fire-set-adm-name').attr('class','fire-set-adm-add').html('+')
        })
        $('.dialog-selec').on('click','li',function(e){
            var _this = this
            $('.fire-set-adm-add').each(function(index,val){
                if($(val).data('active')){
                    $(val).attr('class','fire-set-adm-name')
                    $(val).html($(_this).text()+'<img src="../images/close.png" class="close"/>')
                }
                $('.dialog-selec').hide()
            })
            e.stopPropagation();
        })
        Vue.FireManInfoModel = $.parseJSON(localStorage.getItem('msg'));
        /*if (Vue.getRequest().BrigadeNumber) {
            this.BrigadeNumber = this.getRequest().BrigadeNumber
        } else {

        }*/
        var map = new AMap.Map("container", {
            resizeEnable: true
        });
    },
	methods:{
		showInfoClick(e){
			var Vue = this
			debugger
			console.log(e)
		    var text = '您在 [ '+e.lnglat.getLng()+','+e.lnglat.getLat()+' ] 的位置单击了地图！'
		    this.addMarker(e.lnglat.getLng(),e.lnglat.getLat())
		    this.Pointlng = e.lnglat.getLng()
		    this.PointLat = e.lnglat.getLat()
		    if (this.marker1) {
	           	this.ajaxFirePoint()
	        }
			var col = [this.Pointlng,this.PointLat]
            this.regeocoder(col,Vue)
			//this.openLoading()
		},
	    //创建火灾信息
	    setFireInfo(){
			debugger
	    	var Vue = this
	    	var time = new Date();
			var y = time.getFullYear();
			var m = time.getMonth()+1;
			var d = time.getDate();
			var h = time.getHours();
			var mm = time.getMinutes();
			var s = time.getSeconds();
			var nowTime = y+'-'+this.add0(m)+'-'+this.add0(d)+' '+this.add0(h)+':'+this.add0(mm)+':'+this.add0(s);
			var nowNumer= y+''+this.add0(m)+''+this.add0(d)+''+this.add0(h)+''+this.add0(mm)+''+this.add0(s);
			if(!this.Pointlng){
				this.$message.error('请选择坐标')
				return false
			}
			//this.openLoading()
			console.log(_FireManInfoModel.Fire_brigade_name)
			//console.log(_UserRoleRelationModel)
	    	$.ajax({
		        type: 'post',
		        url:Url+'/FireInfoApi/CreatFireByCoordinate',
		        data: JSON.stringify({
                    Pointlng: ''+Vue.Pointlng+'',
                    PointLat: ''+Vue.PointLat+'',
                    FireNumber: Vue.FireManInfoModel.Fire_brigade_num + nowNumer,
                    CoordinateType: 'gaode',
                    CreateTime : nowTime,
                    FireBrigadeNumber: Vue.FireManInfoModel.Fire_brigade_num,
                    FireBrigadeName: Vue.FireManInfoModel.Fire_brigade_name,
                    FireAddress: Vue.address,

		        }),
		        dataType:'json',
		        contentType: 'application/json',
		        success: function (msg) {		        	
		            if (msg.state == 1) {				      
		            	for(var i = 0;i<Vue.multipleSelection.length;i++ ){
		            		debugger
		            		Vue.multipleSelection[i].Fire_number = msg.data
		            	}
		            	Vue.ajaxSetNotice(msg.data);
		            }else {
		            	Vue.$message.error('创建失败')
		            }

		        }, error: function (XMLHttpRequest, textStatus, errorThrown) {
					console.log(XMLHttpRequest, textStatus, errorThrown)
		        }
	  	  	});
	    },
	    //创建火灾微站通知信息
	    ajaxSetNotice(data){
	    	var Vue = this
	    	$.ajax({
		        type: 'post',
		        url: Url+'FireNotifyApi/FireNotifyCreateAndUpdate',
		        data: JSON.stringify(Vue.multipleSelection),
		        dataType:'json',
		        contentType: 'application/json',
		        success: function (msg) {
		            if (msg.state == 1) {				      
		            	Vue.$message.success('创建成功');
		            	location.href='fire_second.html?FireNumer='+data+'&Pointlng='+Vue.Pointlng+'&PointLat='+Vue.PointLat
		            }else {
		            	Vue.$message.error('创建失败')
		            }
		        }, error: function (XMLHttpRequest, textStatus, errorThrown) {
					console.log(XMLHttpRequest, textStatus, errorThrown)
		        }
	  	  	});
	    },
	    //通过坐标和检索范围，返回周边的微站和所属辖区。
		ajaxFirePoint(){
			var Vue = this
			$.ajax({
		        type: 'post',
		        url: Url+'FireStationApi/GetStationAndAreaCountByFirePoint',
		        data: JSON.stringify({ Pointlng: ''+Vue.Pointlng+'', PointLat: ''+Vue.PointLat+'', Range: Vue.intRange }),
		        dataType:'json',
		        contentType: 'application/json',
		        success: function (msg) {
		            if (msg.state == 1) {
		            	Vue.arrStation = msg.data.FireStationInfoView
		            	Vue.arrAreaInfo = msg.data.AreaInfo
		            	var index = 0
		            	for (var i = 0;i< Vue.arrStation.length;i++) {
		            		var x = Vue.arrStation[i].Gaode_coordinate.split(',')[0]
		            		var y = Vue.arrStation[i].Gaode_coordinate.split(',')[1]
							Vue.addAroundMarker(x,y,i)
							Vue.arrStationCoordinate.push([x,y+index])
		            	}
		            	Vue.selectionStationAll(Vue.arrStation)
                        Vue.ajaxBaiDumap()
		            	setTimeout(function(){
		            		Vue.selectionStationAll(Vue.arrStation)
		            	},10)
		            	
		            }else {
		            	Vue.arrStation = []
		            }

		        }, error: function (XMLHttpRequest, textStatus, errorThrown) {
					console.log(XMLHttpRequest, textStatus, errorThrown)
		        }
	  	  	});
		},
		//修改表格选项
		handleSelectionChange(val) {

			this.arrStationCheckIndex = [];
			for (var i = 0;i<val.length;i++) {
				this.arrStationCheckIndex.push(this.arrStation.indexOf(val[i]))		
			}
			this.clearMarker2()
			for (var i = 0;i<this.arrStationCoordinate.length;i++) {
				this.addAroundMarker(this.arrStationCoordinate[i][0],this.arrStationCoordinate[i][1],i)
			}
			var Vue = this
	        this.multipleSelection = [];
	      
	        var index = 0
	        for(var i = 0;i < val.length;i++){
	        	index = index + 0.02
	        	
	        	this.multipleSelection.push({
	        		Fire_number: '',
	        		Station_number: val[i].Station_number,
	        		Station_name: val[i].Station_name,
	        		Notify_status: 0,
	        	})	      	
	        }		       
	    },
		//全选表格
		selectionStationAll(rows){
			if (rows) {
		          rows.forEach(row => {
		            this.$refs.stationTable.toggleRowSelection(row);
		          });
		        } else {
		          this.$refs.stationTable.clearSelection();
		        }
			},
		//创建坐标
		addMarker(x,y) {
			this.arrStationCoordinate = []
			this.clearMarker1() 
			this.clearMarker2() 
	        this.marker1 = new AMap.Marker({
	            icon: "../images/point_red.png",
	            position: [x,y],
	            offset: new AMap.Pixel(-13, -30)
	        });
	        this.marker1.setMap(this.map);
	        
	   },

	    //创建周围坐标点
	    addAroundMarker(x,y,i) {
	    	var markerContent = '' +
	        '<div class="custom-content-marker">' +
	        '   <img src="../images/point_gray.png">' +
	        '   <div class="close-btn" onclick="clearMarker1">'+i+'</div>' +
	        '</div>';
	  		for (var t=0;t<this.arrStationCheckIndex.length;t++) {
	  			if(i == this.arrStationCheckIndex[t]){		
					markerContent = '' +
			        '<div class="custom-content-marker">' +
			        '   <img src="../images/point_blue.png">' +
			        '   <div class="close-btn" @click="clearMarker2">'+i+'</div>' +
			        '</div>'
	  			}
	  		}
	  		
	        this.marker2 = new AMap.Marker({
	            position: [x,y],
	            content: markerContent,
	            offset: new AMap.Pixel(-13, -30)
	        });
	        this.marker2.setMap(this.map);
	    	this.marker2s.push(this.marker2)
	    },
	    clearMarker1() {
	        if (this.marker1) {
	           this.marker1.setMap(null);
	           this.marker1 = null;
	        }
    	},
    	clearMarker2() {
    		var Vue = this
	        if (this.marker2) {	        	
	        	this.map.remove(this.marker2s);
	        }	       
    	},
    	setRange(e){
    		this.intRange = e.currentTarget.value
    		if (this.marker1) {
	           	this.ajaxFirePoint()
	        }
    	},
    	alertRange(e){
    		this.isShowRange = true
    		$('.rangeList').css({
    			'top' : e.clientY - $(e.currentTarget).offset().top + 'px',
    			'left': e.clientX - $(e.currentTarget).offset().left + 'px'
    		})   	   		
    	},
    	checkRange(item){
    		var Vue = this
    		this.intRange = item ;
    		this.isShowRange = false;
    		if (this.marker1) {
	           	this.ajaxFirePoint()
	        }
    	},
		verifyNum(e){
			e.currentTarget.value = e.currentTarget.value.replace(/\D/g,'')
			if(e.currentTarget.value> 200000){
				e.currentTarget.value = 200000
			}
		},
        ajaxBaiDumap(){
            debugger
            var Vue =this
            var c =  this.Pointlng+','+this.PointLat
            var url = 'http://api.map.baidu.com/geoconv/v1/?coords='+c+'&from=3&to=5&ak=VDoWRq2R6HOZjh1yGCdZzm1RYGOSedgo'
            $.ajax({
                url: url,//根据输入的地址进行地址解析（解析出来输入的地址的经纬度）
                type: 'GET',
                async: false,//设置同步。ajax默认异步
                dataType: 'jsonp',
                jsonp: 'callback',//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(默认为:callback)
                jsonpCallback: "callback",//自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名
                timeout: 5000,
                contentType: 'application/json; charset=utf-8',
                success: function (result) {
                    debugger
                    for(var o =0;o<result.length;o++){
                        Vue.baiduJ = result[o].x;
                        Vue.baiduW = result[o].y
                    }
                }
            })
        },
		add0(m){
			return m<10?'0'+m:m 
		},
        Quit(){
            $.cookie('token', '',{ expires: -1 ,path: '/' });
            window.location.href='../login.html'
        },
        regeocoder(loc,vue) {
			var geocoder,marker;
			if(!geocoder){
				geocoder = new AMap.Geocoder({
					radius: 500 //范围，默认：500
				});
			}
			var lnglat  =loc
			geocoder.getAddress(lnglat, function(status, result) {
				debugger
				if (status === 'complete'&&result.regeocode) {
					debugger
					var address = result.regeocode.formattedAddress;
					var address = address.split("山东省临沂市")
					console.log()
					vue.address = address[1]
					//document.getElementById('address').value = address;
				}else{alert(JSON.stringify(result))}
			});
		}

        /*regeocoder(loc) {  //逆地理编码
			var c = loc[0]+','+loc[1]
            $.ajax({
                url : 'https://restapi.amap.com/v3/geocode/regeo?output=xml&location='+c+'&key=xf-20181013&radius=1000&extensions=all',
                method : 'get'
            }).done(function(msg) {

                //注意获取过来就是一个对象

              var  address = msg.regeocode.formatted_address;
                console.log(address)
               // document.getElementById("result").innerHTML = address;
            });
			/!*debugger
			var geocoder = new AMap.Geocoder({
				radius: 1000,
				extensions: "all"
			});
			geocoder.getAddress(loc, function(status, result) {
				if (status === 'complete' && result.info === 'OK') {
					console.dir(result);
					debugger
					this.geocoder_CallBack(result);
				}
			});*!/

		},
		geocoder_CallBack(data) {
			debugger
			var address = data.regeocode.formattedAddress; //返回地址描述
			//document.getElementById("result").innerHTML = address;
			console.log(address)
		}*/

	}
	
})
